<script setup lang="ts">
import {ref, computed, onMounted, onUnmounted} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {useCartStore} from '../stores/cart.ts'
import {ElMessage} from 'element-plus'
import {fetchSubmitOrder} from "../request/req.ts";
import {formatPrice} from "../util/formatPrice.ts";

const route = useRoute()
const router = useRouter()
const cart = useCartStore()

// 收货地址表单
const addressForm = ref({
  region: '', // 省市区（字符串）
  address: '',
  recipient: '',
  phone: ''
})

// 表单标签位置（移动端置顶）
const formLabelPosition = ref<'left' | 'top'>('left')
const updateLabelPosition = () => {
  formLabelPosition.value = window.innerWidth <= 768 ? 'top' : 'left'
}

// 表单验证规则
const rules = {
  region: [
    {required: true, message: '请选择所在地区', trigger: 'blur'}
  ],
  address: [
    {required: true, message: '请输入详细地址', trigger: 'blur'}
  ],
  recipient: [
    {required: true, message: '请输入收货人姓名', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号码', trigger: 'blur'},
  ]
}

const addressFormRef = ref()

// 订单商品（从购物车获取）
const selectedItems = ref<any[]>([])

// 计算订单总额
const orderTotal = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    return total + (item.price * item.qty)
  }, 0)
})

const shippingFee = 0
const totalAmount = computed(() => orderTotal.value + shippingFee)

// 提交订单
const submitOrder = async () => {
  try {
    await addressFormRef.value.validate()

    // 构建数据
    const orderData = {
      Received: {
        address: addressForm.value.region + ' ' + addressForm.value.address,
        recipient: addressForm.value.recipient,
        phone: addressForm.value.phone
      },
      Order: selectedItems.value.map(item => ({
        Id: item.id,
        count: item.qty,
      }))
    };

    // 将数据转换为字符串
    const orderDataString = JSON.stringify(orderData)

    const formData = new FormData()
    formData.append('o', orderDataString)

    const res = await fetchSubmitOrder(formData)
    if (res ) {
      ElMessage.success('订单提交成功！')

      // 清空购物车中已下单的商品
      selectedItems.value.forEach(item => {
        cart.remove(item.id)
      })

      await router.push({
        path: '/order-success',
        query: {
          id: res.CartOrders,
        }
      })
    } else {
      ElMessage.error(res?.message || '订单提交失败，请重试')
    }
  } catch (error) {
    console.error('表单验证失败或提交失败:', error)
    ElMessage.error('订单提交失败，请检查表单信息')
  }
}

// 页面加载时获取购物车数据
onMounted(() => {
  // 从路由参数获取选中的商品ID列表
  const selectedIds = route.query.selectedIds
  if (selectedIds) {
    const ids = Array.isArray(selectedIds) ? selectedIds : [selectedIds]
    selectedItems.value = cart.items.filter(item => ids.includes(item.id.toString()))
  } else {
    // 如果没有传递选中商品，显示购物车所有商品
    selectedItems.value = [...cart.items]
  }

  // 如果没有商品，跳转回购物车
  if (selectedItems.value.length === 0) {
    ElMessage.warning('购物车中没有商品')
    router.push('/cart')
  }

  updateLabelPosition()
  window.addEventListener('resize', updateLabelPosition)
})

onUnmounted(() => {
  window.removeEventListener('resize', updateLabelPosition)
})
</script>

<template>
  <div class="order-page">
    <div class="order-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1 style="color: white">確認訂單</h1>
      </div>

      <!-- 收货信息 -->
      <div class="section address-section">
        <h2 style="color: white">收穫信息</h2>
        <el-form
            ref="addressFormRef"
            :model="addressForm"
            :rules="rules"
            label-width="100px"
            :label-position="formLabelPosition"
            class="address-form"
        >
          <el-form-item label="收貨地址" prop="region">
            <el-input
                v-model="addressForm.region"
                placeholder="請輸入省/市/區"
                style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="詳細地址" prop="address">
            <el-input
                v-model="addressForm.address"
                type="textarea"
                :rows="3"
                placeholder="詳細地址、街道、門牌號等"
                style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="收貨人" prop="recipient">
            <el-input
                v-model="addressForm.recipient"
                placeholder="請輸入收貨人名稱"
                style="width: 200px"
            />
          </el-form-item>

          <el-form-item label="手機號碼" prop="phone">
            <el-input
                v-model="addressForm.phone"
                placeholder="請輸入手機號碼"
                style="width: 200px"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 订单商品 -->
      <div class="section order-section">
        <h2 style="color: white">訂單商品</h2>
        <div class="order-items">
          <!-- 商品列表 -->
          <div
            v-for="item in selectedItems"
            :key="item.id"
            class="order-item"
          >
            <div class="item-info">
              <img :src="item.image" :alt="item.title" class="item-image"/>
              <div class="item-details">
                <h3 class="item-title">{{ item.title }}</h3>
              </div>
            </div>
            <div class="item-price">HK$ {{ formatPrice(item.price) }}</div>
            <div class="item-qty">{{ item.qty }}</div>
            <div class="item-subtotal">HK$ {{ formatPrice(item.price * item.qty) }}</div>
          </div>
        </div>
      </div>

      <!-- 订单汇总 -->
      <div class="section summary-section">
        <div class="summary-content">
          <div class="summary-item">
            <span style="color: white">商品合計:</span>
            <span class="amount">HK$ {{ formatPrice(orderTotal) }}</span>
          </div>
          <div class="summary-item">
            <span style="color: white">運費:</span>
            <span class="amount">HK$ {{ shippingFee.toFixed(2) }}</span>
          </div>
          <div class="summary-item total">
            <span style="color: white">應付總額:</span>
            <span class="amount total-amount">HK$ {{formatPrice(totalAmount) }}</span>
          </div>
        </div>
      </div>

      <div class="submit-section">
        <el-button
            type="danger"
            size="large"
            @click="submitOrder"
            :disabled="selectedItems.length === 0"
        >
          提交訂單
        </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.order-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.order-container {
  background-color: #2c3e50;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.page-header {
  padding: 20px;
  text-align: center;
}

.page-header h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.section {
  padding: 20px;
}

.section h2 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.address-form {
  max-width: 600px;
}

.address-form :deep(.el-form-item__label) {
  font-size: 16px;
  color: #d1d1d1 !important;
  font-weight: 600 !important;
}

.order-items {
  border-radius: 6px;
  overflow: hidden;
}

.order-item {
  display: grid;
  grid-template-columns: 1fr 120px 100px 120px;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #4a5f73;
}

.order-item:last-child {
  border-bottom: none;
}



.item-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 6px;
}

.item-title {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: rgba(224, 224, 224, 0.81);
}

.item-price, .item-qty, .item-subtotal {
  font-size: 14px;
  font-weight: 600;
  color: rgba(224, 224, 224, 0.81);
}

.summary-content {
  max-width: 400px;
  margin-left: auto;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 14px;
}

.summary-item.total {
  border-top: 1px solid #ddd;
  margin-top: 8px;
  padding-top: 16px;
  font-size: 16px;
  font-weight: 600;
}

.amount {
  color: rgba(224, 224, 224, 0.81);
  font-weight: 600;
}

.total-amount {
  font-size: 20px;
  font-weight: 800;
}

.submit-section {
  padding: 20px;
  text-align: center;
}

@media (max-width: 768px) {
  .order-page {
    padding: 10px;
  }

  .section {
    padding: 15px;
  }

  .address-form { max-width: 100%; }

  .order-item {
    grid-template-columns: 1fr 1fr 1fr;
    gap: 10px;
  }

  .item-info { grid-column: 1 / -1; }
  .item-price, .item-qty, .item-subtotal { justify-self: end; }
  .item-image { width: 54px; height: 54px; }

  .summary-content {
    margin: 0;
    max-width: 100%;
  }

}

@media (max-width: 480px) {
  .page-header h1 { font-size: 20px; }
  .section h2 { font-size: 16px; }
  .item-title { font-size: 13px; }
  .summary-item { font-size: 13px; }
  .total-amount { font-size: 18px; }
}
</style>
